import os
import sys
import logging
sys.path.append(os.path.join(os.path.dirname(__file__), 'modules'))
sys.path.append(os.path.join(os.path.dirname(__file__), 'json'))
sys.path.append(os.path.dirname(__file__))
import json
import service
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app


class MainPage(webapp.RequestHandler):
    def forward(self):
      template_values = {
      }
      path = os.path.join(os.path.dirname(__file__), '../site/index.html')
      self.response.out.write(template.render(path, template_values))

    def get(self): 
        self.forward()

    def post(self):
        self.forward()

class ServiceDispatcher(webapp.RequestHandler):
    def post(self):
        url = cutUrlFromPrefix(self.request.path_info,"/service")
        if(url == '/doInit'):
            service.doInit(self) 
        elif(url == '/doDispatcher'):
            service.doDispatcher(self)
        elif(url == '/doLogin'):
            service.doLogin(self)
        elif(url == '/doLogout'):
            service.doLogout(self)
        else:
            if(service.isLogined()):
                if(url == '/showCatalogTree'):
                    service.showCatalogTree(self)
                elif(url == '/showAccountList'):
                    service.showAccountList(self)
                elif(url == '/showAccount'):
                    service.showAccount(self)
                elif(url == '/showCatalog'):
                    service.showCatalog(self)
                elif(url == '/newCatalog'):
                    service.newCatalog(self)
                elif(url == '/modifyCatalog'):
                    service.modifyCatalog(self)
                elif(url == '/deleteCatalog'):
                    service.deleteCatalog(self)
                elif(url == '/newAccount'):
                    service.newAccount(self)
                elif(url == '/modifyAccount'):
                    service.modifyAccount(self)
                elif(url == '/deleteAccount'):
                    service.deleteAccount(self)
            else:
                self.error(404)     
            
    def get(self):
         url = cutUrlFromPrefix(self.request.path_info,"/service")
         if(url == '/doClearuser'):
             service.doClearUser(self) 

def cutUrlFromPrefix (url, prefix):
    if url.startswith(prefix):
        nopre = url[len(prefix) : ]
        if nopre.startswith("/"):
            return nopre
        else:
            return "/" + nopre
    else:
        return url

    
application = webapp.WSGIApplication(
                                     [('/service/.*', ServiceDispatcher),
                                     ('/.*', MainPage),],
                                     debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()